#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDataStream>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    inputFile = nullptr;
}

MainWindow::~MainWindow()
{
    delete ui;
    if(inputFile) delete inputFile;
}

void MainWindow::on_browseButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(
        this, "选择BIN文件", "", "Binary Files (*.bin)");
    
    if(!fileName.isEmpty()){
        ui->filePathEdit->setText(fileName);
        inputFile = new QFile(fileName);
    }
}

void MainWindow::on_startButton_clicked()
{
    if(!inputFile || !inputFile->exists()){
        QMessageBox::critical(this, "错误", "请先选择有效的BIN文件");
        return;
    }

    quint64 chunkSize = static_cast<quint64>(ui->chunkSizeSpin->value()) * 1024;
    if(chunkSize == 0){
        QMessageBox::critical(this, "错误", "无效的分割大小");
        return;
    }

    if(splitFile(inputFile->fileName(), chunkSize)){
        QMessageBox::information(this, "完成", "文件分割成功!");
        ui->progressBar->setValue(0);
    }
}

bool MainWindow::splitFile(const QString &path, quint64 chunkSize)
{
    if(!inputFile->open(QIODevice::ReadOnly)){
        QMessageBox::critical(this, "错误", "无法打开文件");
        return false;
    }

    quint64 totalSize = inputFile->size();
    quint64 chunks = totalSize / chunkSize + (totalSize % chunkSize ? 1 : 0);
    quint64 bytesWritten = 0;
    QDataStream in(inputFile);
    
    for(quint64 i = 0; i < chunks; ++i){
        QFile outFile(path + QString(".part%1").arg(i+1));
        if(!outFile.open(QIODevice::WriteOnly)){
            QMessageBox::critical(this, "错误", "无法创建输出文件");
            return false;
        }

        QDataStream out(&outFile);
        quint64 remaining = totalSize - bytesWritten;
        quint64 writeSize = qMin(remaining, chunkSize);
        char *buffer = new char[writeSize];
        
        in.readRawData(buffer, writeSize);
        out.writeRawData(buffer, writeSize);
        delete[] buffer;
        
        bytesWritten += writeSize;
        ui->progressBar->setValue(static_cast<int>((bytesWritten * 100)/totalSize));
        outFile.close();
    }

    inputFile->close();
    return true;
}
